package com.umeox.zikrringtest.auto_close.search

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import com.umeox.logger.UMLogger
import com.umeox.zikrringtest.auto_close.deviceManager.Device
import com.umeox.zikrringtest.auto_close.deviceManager.DeviceListManager
import com.umeox.sdk_ring.RingScanCallback
import com.umeox.sdk_ring.UMScanResult
import com.umeox.sdk_ring.scan.RingScanner

private const val TAG = "DeviceSearchManager"
object DeviceSearchManager {

    val versionNoSupportDeviceList = arrayListOf<String>()

    private val handler = Handler(Looper.getMainLooper())

    private val lossCheckTask = Runnable {
        if (waitSize > 0) {
            requestDeviceJoin()
        }
    }

    /**
     * 处理设备中
     */
    private var progressing = false

    private var waitSize = 0

    @SuppressLint("MissingPermission")
    private val call: RingScanCallback = object : RingScanCallback {
        override fun onScanResult(result: UMScanResult) {
            if (progressing || versionNoSupportDeviceList.contains(result.device.address)) {
                return
            }

            val regexList = "Zikr.*".split(",")
            for (regex in regexList) {
                val nameRegex = Regex(regex)
                if (!TextUtils.isEmpty(result.device.name) && (result.device.name.matches(
                        nameRegex
                    ))
                ) {
                    progressing = true
                }
            }
            if (progressing) {
                scannerManager.stopScan()
                val device = Device()
                device.name = result.device.name
                device.mac = result.device.address
                device.rssi = result.rssi
                DeviceListManager.addDevice(device)
                waitSize--
                if (waitSize > 0) {
                    handler.postDelayed(lossCheckTask,10*1000)
                }
            }
        }
    }

    private val scannerManager = RingScanner(this, call, Handler(Looper.getMainLooper()))


    fun requestDeviceJoin() {
        UMLogger.d(TAG,"开始扫描任务")
        progressing = false
        waitSize++
        scannerManager.startScan()
    }
}